import user from '../../api/user'
import * as types from '../mutation-types.js'

const state = {
  userData: [],
  userNotice: [],
  userErr: []
}

const getters = {
  userData: state => state.userData,
  userNotice: state => state.userNotice,
  userErr: state => state.userErr
}

const actions = {
  getUserDatas ({commit}) {
    return new Promise((resolve, reject) => {
      user.getUserDatas()
        .then(data => {
          commit(types.GET_USERDATA, data)
          resolve()
        })
        .catch(err => {
          commit(types.ERR_USER, err)
        })
    })
  },
  deleteUser ({commit, dispatch}, {userId}) {
    return new Promise((resolve, reject) => {
      user.deleteUser(userId)
        .then(data => {
          commit(types.USER_NOTICE, '删除管理员成功')
          dispatch('getUserDatas')
          resolve()
        })
        .catch(err => {
          commit(types.ERR_USER, err)
        })
    })
  },
  addUser ({commit, dispatch}, newUser) {
    return new Promise((resolve, reject) => {
      user.addUser(newUser)
        .then(data => {
          commit(types.USER_NOTICE, '添加管理员成功')
          dispatch('getUserDatas')
          resolve()
        })
        .catch(err => {
          commit(types.ERR_USER, err)
        })
    })
  }
}

const mutations = {
  [types.GET_USERDATA] (state, data) {
    state.userData = data
  },
  [types.USER_NOTICE] (state, data) {
    state.userNotice.push({msg: data})
  },
  [types.ERR_USER] (state, err) {
    state.userErr.push({msg: err})
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
